<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { cloneDeep } from 'lodash-es';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { videoMonitorCreateApi, videoMonitorEditApi } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import { breedingPondManageHooks } from '@/views/breedingManage/breedingPondManage/breedingPondManageHooks';
const projectStore = useProjectStore();
defineOptions({
    name: 'GetewayOperateDrawer'
});

// 获取网关数据
const { getFarmList } = breedingPondManageHooks();
const farmData: any = ref([]);

onMounted(async () => {
    farmData.value = await getFarmList(projectStore.currentProject?.id);
});

interface Props {
    operateType: AntDesign.TableOperateType;
    rowData?: any | null;
}

const props = defineProps<Props>();

interface Emits {
    (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
    default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
    const titles: Record<AntDesign.TableOperateType, string> = {
        add: '新增监控视频设备',
        edit: '编辑监控视频设备'
    };
    return titles[props.operateType];
});

const model: any = reactive(createDefaultModel());

function createDefaultModel(): any {
    return {};
}

const rules: any = {
    name: defaultRequiredRule,
    serialNumber: defaultRequiredRule,
    farmIds: defaultRequiredRule,
};

/** the enabled role options */
async function handleInitModel() {
    Object.assign(model, createDefaultModel());

    if (props.operateType === 'edit' && props.rowData) {
        await nextTick();
        const newData = cloneDeep(props.rowData);
        if (props.rowData.farmIds) {
            newData.farmIds = props.rowData.farmIds.split(';').map(Number);
        }
        Object.assign(model, newData);
    }
}

function closeDrawer() {
    visible.value = false;
}

// eslint-disable-next-line no-warning-comments
/* TODO 设备编码不填写不行， 后面要删掉 */

const doAddSubmit = async () => {
    const res = await videoMonitorCreateApi({
        ...model,
        projectId: projectStore.currentProject?.id,
        farmIds: model.farmIds.join(';')
    });
    if (res.error === null) {
        window.$message?.success('新增成功');
        closeDrawer();
        emit('submitted');
    }
};
const doEditSubmit = async () => {
    const res = await videoMonitorEditApi({
        ...model,
        farmIds: model.farmIds.join(';')
    });
    if (res.error === null) {
        window.$message?.success('更新成功');
        closeDrawer();
        emit('submitted');
    }
};

async function handleSubmit() {
    await validate();
    if (props.operateType === 'add') {
        await doAddSubmit();
    }
    if (props.operateType === 'edit') {
        await doEditSubmit();
    }
}

watch(visible, () => {
    if (visible.value) {
        handleInitModel();
        resetFields();
    }
});
</script>

<template>
    <AModal v-model:open="visible" :title="title" :width="560" :mask-closable="false">
        <AForm ref="formRef" layout="vertical" :model="model" :rules="rules">
            <AFormItem label="监控名称" name="name">
                <AInput v-model:value="model.name" placeholder="请输入监控名称" />
            </AFormItem>
            <AFormItem label="设备序列号" name="serialNumber">
                <AInput v-model:value="model.serialNumber" placeholder="请输入设备序列号" />
            </AFormItem>
            <AFormItem label="设备通道号" name="channelNo">
                <AInput v-model:value="model.channelNo" placeholder="通道号，非必选" />
            </AFormItem>
            <AFormItem label="养殖池" name="farmIds">
                <ASelect v-model:value="model.farmIds" placeholder="请选择养殖池" mode="multiple">
                    <ASelectOption v-for="item in farmData" :key="item.id" :value="item.id">
                        {{ item.name }}
                    </ASelectOption>
                </ASelect>
            </AFormItem>
            <AFormItem label="序号" name="sequence">
                <AInputNumber :min="1" class="w-full" v-model:value="model.sequence" placeholder="请输入序号, 序号越小列表越靠前" />
            </AFormItem>
            <AFormItem label="备注" name="remark">
                <ATextarea v-model:value="model.remark" placeholder="请输入备注" />
            </AFormItem>
        </AForm>
        <template #footer>
            <ASpace :size="16">
                <AButton @click="closeDrawer">取消</AButton>
                <AButton type="primary" @click="handleSubmit">确认</AButton>
            </ASpace>
        </template>
    </AModal>
</template>

<style scoped></style>
